<template>
<section id="partial-bind-phone" class="panel card">
    <header class="panel__header">
      <h3>绑定手机号</h3>
      <p>
        当前登录流程需要绑定手机号并设置登录密码。完成后即可同步企业数据，继续进行企业认证或进入商城。
      </p>
    </header>

    <el-alert
      type="info"
      :closable="false"
      class="panel__alert"
      title="提示"
      :description="hintMessage"
    />

    <form class="panel__form" @submit.prevent="handleSubmit">
      <label class="panel__field">
        <span>手机号</span>
        <input
          v-model.trim="form.phone"
          type="tel"
          maxlength="11"
          placeholder="请输入 11 位手机号"
          required
        />
      </label>
      <div class="panel__row">
        <label class="panel__field panel__field--flex">
          <span>短信验证码</span>
          <input
            v-model.trim="form.code"
            type="text"
            maxlength="6"
            placeholder="请输入验证码"
            required
          />
        </label>
        <button
          type="button"
          class="btn btn--ghost"
          :disabled="countdown > 0 || sending"
          @click="handleSendCode"
        >
          {{ countdown > 0 ? `${countdown}s` : "获取验证码" }}
        </button>
      </div>
      <label class="panel__field">
        <span>登录密码（可选）</span>
        <input
          v-model="form.password"
          type="password"
          minlength="6"
          placeholder="设置密码便于后续直接登录"
        />
      </label>
      <label class="panel__field">
        <span>联系人 / 昵称（可选）</span>
        <input
          v-model.trim="form.nickname"
          type="text"
          placeholder="用于会员中心展示"
        />
      </label>

      <button type="submit" class="btn btn--primary" :disabled="submitting">
        {{ submitting ? "绑定中..." : "完成绑定并继续" }}
      </button>
    </form>
  </section>
</template>

<script setup>
import { computed, onUnmounted, reactive, ref } from "vue";
import { sendSmsCode, register } from "../../api/auth";
import { message } from "../../utils/message";
import { useUserStore } from "../../store/user";

const props = defineProps({
  partial: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(["completed"]);

const userStore = useUserStore();
const form = reactive({
  phone: "",
  code: "",
  password: "",
  nickname: ""
});
const sending = ref(false);
const submitting = ref(false);
const countdown = ref(0);
let timer = null;

const identifier = computed(() => props.partial?.context?.identifier || "");
const hintMessage = computed(() => {
  if (identifier.value) {
    return `检测到第三方账号「${identifier.value}」，请绑定手机号后继续使用。`;
  }
  return "请绑定常用手机号以便接收核实、订单等通知。";
});

const startCountdown = () => {
  countdown.value = 60;
  timer = window.setInterval(() => {
    countdown.value -= 1;
    if (countdown.value <= 0 && timer) {
      window.clearInterval(timer);
      timer = null;
    }
  }, 1000);
};

const validatePhone = () => /^1\d{10}$/.test(form.phone);

const handleSendCode = async () => {
  if (!props.partial?.token) {
    message.error("部分令牌失效，请重新登录");
    return;
  }
  if (!validatePhone()) {
    message.warning("请输入有效的手机号");
    return;
  }
  try {
    sending.value = true;
    await sendSmsCode({ phone: form.phone, scene: "bind" });
    message.success("验证码已发送，请注意查收");
    startCountdown();
  } catch (error) {
    message.error(error.message || "验证码发送失败");
  } finally {
    sending.value = false;
  }
};

const handleSubmit = async () => {
  if (!props.partial?.token) {
    message.error("部分令牌失效，请重新登录");
    return;
  }
  if (!validatePhone()) {
    message.warning("请输入有效的手机号");
    return;
  }
  if (!form.code || form.code.length < 4) {
    message.warning("请输入正确的验证码");
    return;
  }
  submitting.value = true;
  try {
    const response = await register({
      phone: form.phone,
      code: form.code,
      password: form.password || undefined,
      nickname: form.nickname || undefined,
      partial_token: props.partial.token
    });
    const result = userStore.consumeAuthResponse(response);
    if (result.type === "token") {
      message.success("手机号绑定成功，已自动登录");
    } else {
      message.success(result.message || "绑定成功，请继续完成后续步骤");
    }
    emit("completed", result.payload);
  } catch (error) {
    message.error(error.message || "绑定失败，请重试");
  } finally {
    submitting.value = false;
  }
};

onUnmounted(() => {
  if (timer) {
    window.clearInterval(timer);
    timer = null;
  }
});
</script>

<style scoped lang="scss">
.panel {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 28px;
}

.panel__header {
  display: flex;
  flex-direction: column;
  gap: 8px;

  h3 {
    margin: 0;
  }

  p {
    margin: 0;
    color: var(--gray-600);
  }
}

.panel__alert {
  border-radius: 12px;
}

.panel__form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.panel__field {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-size: 14px;
  color: var(--gray-600);

  input {
    border: 1px solid var(--gray-200);
    border-radius: 10px;
    padding: 10px 14px;

    &:focus {
      border-color: var(--primary-color);
      outline: none;
      box-shadow: 0 0 0 3px rgba(0, 82, 217, 0.16);
    }
  }
}

.panel__field--flex {
  flex: 1;
}

.panel__row {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.btn {
  border-radius: 10px;
  border: none;
  padding: 10px 18px;
  font-weight: 600;
  cursor: pointer;

  &--primary {
    background: var(--primary-color);
    color: #fff;
  }

  &--ghost {
    background: var(--gray-100);
    color: var(--primary-color);
  }
}
</style>
